/*
 * @(#) DatabaseAction.java Oct 8, 2011
 *
 * Copyright (c) 2011, Strong Technology. All Rights Reserved.
 * Strong Technology. CONFIDENTIAL
 */
package cn.strong.gweva.system.presentation.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import cn.strong.gweva.common.business.entity.PagerEntity;
import cn.strong.gweva.common.presentation.action.AjaxBaseAction;
import cn.strong.gweva.common.util.DateUtil;


/**
 * 数据备份与还原Action.
 * 
 * @author jincong
 * @version 1.0
 * @since Oct 8, 2011
 */
public class DatabaseAction extends AjaxBaseAction
{

	/** serialVersionUID */
	private static final long serialVersionUID = 161590232127419719L;

	/** 还原数据文件 */
	private String importFile;

	/** 备份文件分页 */
	private PagerEntity pagerEntity;

	/**
	 * 数据备份与还原
	 * 
	 * @return
	 */
	public String operation()
	{
		try
		{
			String path = ServletActionContext.getServletContext().getRealPath("database");
			File folder = new File(path);

			if (folder.exists())
			{
				String[] files = folder.list(new FilenameFilter() {

					public boolean accept(File dir, String fileName)
					{
						return fileName.endsWith(".sql");
					}
				});

				if (this.pagerEntity == null)
				{
					this.pagerEntity = new PagerEntity();
				}

				if (this.pagerEntity.getPageInfo().getPageSize() == null)
				{
					this.pagerEntity.getPageInfo().setPageSize(new BigDecimal(15));
				}

				this.pagerEntity.getPageInfo().setPageCount(new BigDecimal(files.length));

				int count = 0;
				List<Object> list = new ArrayList<Object>();
				for (int i = this.pagerEntity.getPageInfo().getPageStart().intValue(); count < this.pagerEntity
						.getPageInfo().getPageSize().intValue();)
				{
					if (i == files.length)
					{
						break;
					}
					list.add(files[i]);
					count++;
					i++;
				}
				this.pagerEntity.setResultList(list);
			}
		}
		catch (Exception e)
		{
			return processException(e);
		}

		return LIST;
	}

	/**
	 * 备份数据.
	 * 
	 * @return
	 */
	public String doExport()
	{
		OutputStream os = null;
		InputStream is = null;

		try
		{
			String path = ServletActionContext.getServletContext().getRealPath("database");

			// 打开cmd进程
			Process process = Runtime.getRuntime().exec("cmd /k");

			os = process.getOutputStream();
			is = process.getInputStream();

			// 进入指定目录
			runCommand(os, "cd /d " + path + " \n");
			// 执行备份命令
			runCommand(os, path + "\\export.bat " + DateUtil.formatDate(new Date(), DateUtil.DATE_PATTERN_03) + " \n");
//			runCommand(os, "mysqldump.exe --default-character-set=gb2312 -uroot -proot gweva > " + DateUtil.formatDate(new Date(), DateUtil.DATE_PATTERN_03) + ".sql \n");
			// 退出
			runCommand(os, "exit\n");

			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			while (true)
			{
				String s = br.readLine();
				if (s == null)
				{
					break;
				}
			}
			br.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (os != null)
				{
					os.close();
				}
				if (is != null)
				{
					is.close();
				}
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		return this.operation();
	}

	public String doImport()
	{
		OutputStream os = null;
		InputStream is = null;

		try
		{
			String path = ServletActionContext.getServletContext().getRealPath("database");

			// 打开cmd进程
			Process process = Runtime.getRuntime().exec("cmd /k");

			os = process.getOutputStream();
			is = process.getInputStream();

			// 进入指定目录
			runCommand(os, "cd /d " + path + " \n");
			// 执行还原命令
			runCommand(os, path + "\\import.bat " + this.importFile + " \n");
//			runCommand(os, "mysql.exe --default-character-set=gb2312 -uroot -proot gweva < " + this.importFile + " \n");
			// 退出
			runCommand(os, "exit\n");

			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			while (true)
			{
				String s = br.readLine();
				if (s == null)
				{
					break;
				}
			}
			br.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (os != null)
				{
					os.close();
				}
				if (is != null)
				{
					is.close();
				}
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		return this.operation();
	}

	/**
	 * 下载数据文件.
	 */
	public void doDownload()
	{
		OutputStream output = null;
		InputStream input = null;

		try
		{

			// 只下载.sql文件
			if (!this.importFile.endsWith(".sql"))
			{
				return;
			}

			// 只下载当前目录下的
			this.importFile = this.importFile.substring(this.importFile.lastIndexOf(System
					.getProperty("file.separator")) + 1);

			// 存放目录
			String path = ServletActionContext.getServletContext().getRealPath("database");
			// 下载的文件
			File file = new File(path + "\\" + this.importFile);

			input = new FileInputStream(file);

			byte[] contents = new byte[(int)file.length()];
			input.read(contents);

			this.getResponse().setContentType("text/html");
			this.getResponse().setHeader(
					"Content-Disposition",
					"attachment;filename="
							+ new String(this.importFile.getBytes("gb2312"), "ISO8859-1"));
			this.getResponse().getOutputStream().write(contents);
			this.getResponse().getOutputStream().flush();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (input != null)
			{
				try
				{
					input.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}

			if (output != null)
			{
				try
				{
					output.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 执行命令.
	 * 
	 * @param os
	 * @param command
	 * @throws IOException
	 */
	private void runCommand(OutputStream os, String command) throws IOException
	{
		os.write(command.getBytes());
		os.flush();
	}

	/**
	 * 设定还原数据文件.
	 * 
	 * @param importFile 还原数据文件
	 */
	public void setImportFile(String importFile)
	{
		this.importFile = importFile;
	}

	/**
	 * 获取还原数据文件.
	 * 
	 * @return 还原数据文件
	 */
	public String getImportFile()
	{
		return this.importFile;
	}

	/**
	 * 设定备份文件分页.
	 * 
	 * @param pagerEntity 备份文件分页
	 */
	public void setPagerEntity(PagerEntity pagerEntity)
	{
		this.pagerEntity = pagerEntity;
	}

	/**
	 * 获取备份文件分页.
	 * 
	 * @return 备份文件分页
	 */
	public PagerEntity getPagerEntity()
	{
		return this.pagerEntity;
	}

}
